from django.shortcuts import render
from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from movie.models import Movie
from .serializers import UserCollectionSerializer

class CollectViewSet(viewsets.ViewSet):
    permission_classes = [IsAuthenticated]
    serializer_class = UserCollectionSerializer

    def get_standard_response(self, code, message, data=None):
        return {
            "code": code,
            "message": message,
            "data": data
        }

    def list(self, request):
        """获取用户收藏列表"""
        try:
            collected_movies = request.user.collected_movies.all()
            serializer = self.serializer_class(collected_movies, many=True)
            return Response(self.get_standard_response(
                code=200,
                message="获取收藏列表成功",
                data={
                    "total": collected_movies.count(),
                    "items": serializer.data
                }
            ))
        except Exception as e:
            return Response(self.get_standard_response(
                code=500,
                message=f"获取收藏列表失败：{str(e)}",
                data=None
            ), status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    @action(detail=False, methods=['post'])
    def add(self, request):
        """添加收藏"""
        try:
            movie_id = request.data.get('movie_id')
            if not movie_id:
                return Response(self.get_standard_response(
                    code=400,
                    message="电影ID不能为空",
                    data=None
                ), status=status.HTTP_400_BAD_REQUEST)

            movie = Movie.objects.get(id=movie_id)
            
            if request.user.collected_movies.filter(id=movie_id).exists():
                return Response(self.get_standard_response(
                    code=400,
                    message="已经收藏过该电影",
                    data=None
                ), status=status.HTTP_400_BAD_REQUEST)

            movie.collectors.add(request.user)
            return Response(self.get_standard_response(
                code=200,
                message="收藏成功",
                data=None
            ))
        except Movie.DoesNotExist:
            return Response(self.get_standard_response(
                code=404,
                message="电影不存在",
                data=None
            ), status=status.HTTP_404_NOT_FOUND)
        except Exception as e:
            return Response(self.get_standard_response(
                code=500,
                message=f"收藏失败：{str(e)}",
                data=None
            ), status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    @action(detail=False, methods=['post'])
    def remove(self, request):
        """取消收藏"""
        try:
            movie_id = request.data.get('movie_id')
            if not movie_id:
                return Response(self.get_standard_response(
                    code=400,
                    message="电影ID不能为空",
                    data=None
                ), status=status.HTTP_400_BAD_REQUEST)

            movie = Movie.objects.get(id=movie_id)
            movie.collectors.remove(request.user)
            
            return Response(self.get_standard_response(
                code=200,
                message="取消收藏成功",
                data=None
            ))
        except Movie.DoesNotExist:
            return Response(self.get_standard_response(
                code=404,
                message="电影不存在",
                data=None
            ), status=status.HTTP_404_NOT_FOUND)
        except Exception as e:
            return Response(self.get_standard_response(
                code=500,
                message=f"取消收藏失败：{str(e)}",
                data=None
            ), status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    @action(detail=False, methods=['get'])
    def check(self, request):
        """检查电影是否已收藏"""
        try:
            movie_id = request.query_params.get('movie_id')
            if not movie_id:
                return Response(self.get_standard_response(
                    code=400,
                    message="电影ID不能为空",
                    data=None
                ), status=status.HTTP_400_BAD_REQUEST)

            is_collected = request.user.collected_movies.filter(id=movie_id).exists()
            
            message = "该电影已收藏" if is_collected else "该电影未收藏"
            
            return Response(self.get_standard_response(
                code=200,
                message=message,
                data={'is_collected': is_collected}
            ))
        except Exception as e:
            return Response(self.get_standard_response(
                code=500,
                message=f"检查收藏状态失败：{str(e)}",
                data=None
            ), status=status.HTTP_500_INTERNAL_SERVER_ERROR)

